package com.zq.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zq.product.config.ExcelListener;
import com.zq.product.dao.dto.ProductAddDto;
import com.zq.product.dao.entity.Category;
import com.zq.product.dao.entity.Product;
import com.zq.product.dao.dto.ProductDto;
import com.zq.product.dao.entity.ProductDetails;
import com.zq.product.dao.entity.ProductSku;
import com.zq.product.dao.vo.CategoryExcelVo;
import com.zq.product.dao.vo.ProductExcelVo;
import com.zq.product.dao.vo.ProductVo;
import com.zq.product.mapper.ProductMapper;
import com.zq.product.service.IProductDetailsService;
import com.zq.product.service.IProductService;
import com.zq.product.service.IProductSkuService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2025-05-13
 */
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Resource
    private ProductMapper productMapper;


    //    商品分页查询
    @Override
    public PageInfo<ProductVo> findByPage(Integer page, Integer limit,
                                          ProductDto productDto) {

        PageHelper.startPage(page, limit);
List<ProductVo> productList= productMapper.findByPage( productDto);

PageInfo<ProductVo> pageInfo = new PageInfo<>(productList);
        return pageInfo;
    }
@Resource
private IProductSkuService productSkuService;
    @Resource
    private IProductDetailsService productDetailsService;


    //    商品添加
    @Transactional
    @Override
    public void addProduct(ProductAddDto productAddDto) {
        // 保存商品数据
        productAddDto.setStatus(-1);              // 设置上架状态为0
        productAddDto.setAuditStatus(0);         // 设置审核状态为0
        Product product = new Product();
        BeanUtils.copyProperties(productAddDto, product);
        this.save(product);

        productAddDto.setId(product.getId());    // 设置商品id

        // 保存商品sku数据
        List<ProductSku> productSkuList = productAddDto.getProductSkuList();
        for(int i=0,size=productSkuList.size(); i<size; i++) {
            // 获取ProductSku对象
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);       // 构建skuCode

            productSku.setProductId(product.getId());               // 设置商品id
            productSku.setSkuName(product.getName() + productSku.getSkuSpec());
            productSku.setSaleNum(0);                               // 设置销量
            productSku.setStatus(0);
            productSkuService.save(productSku);                    // 保存数据

        }

        // 保存商品详情数据
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(product.getId());
        productDetails.setImageUrls(productAddDto.getDetailsImageUrls());
        productDetailsService.save(productDetails);

    }

    @Override
    public ProductVo getByIdApi(Long id) {
        // 根据id查询商品数据
        ProductVo productVo = productMapper.selectByIdApi(id);
        // 根据商品的id查询sku数据
        List<ProductSku> productSkuList = productSkuService.list(new LambdaQueryWrapper<ProductSku>()
                .eq(ProductSku::getProductId,id));
        productVo.setProductSkuList(productSkuList);
        // 根据商品的id查询商品详情数据
        ProductDetails productDetails =productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>()
                .eq(ProductDetails::getProductId,id));
        if (productDetails == null) {
            throw new RuntimeException("商品详情数据不存在");
        }
        // 商品详情数据赋值
        productVo.setDetailsImageUrls(productDetails.getImageUrls());
        return productVo;
    }

    @Transactional
    @Override
    public void updateByIdApi(ProductVo productVo) {
        Product product = new Product();
        BeanUtils.copyProperties(productVo, product);
        // 修改商品基本数据
        this.updateById(product);

        // 修改商品的sku数据
        List<ProductSku> productSkuList = productVo.getProductSkuList();
        productSkuList.forEach(productSku -> {
            productSkuService.updateById(productSku);
        });

        // 修改商品的详情数据
        ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>()
                .eq(ProductDetails::getProductId,productVo.getId()));
        productDetails.setImageUrls(productVo.getDetailsImageUrls());
        productDetailsService.updateById(productDetails);
    }

    //根据id删除商品
    @Transactional
    @Override
    public void deleteById(Long id) {
        this.removeById(id);                   // 根据id删除商品基本数据
        // 根据商品id删除商品的sku数据
        productSkuService.remove(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId,id));
        // 根据商品的id删除商品的详情数据
        productDetailsService.remove(new LambdaQueryWrapper<ProductDetails>().
                eq(ProductDetails::getProductId,id));

    }


    //根据id修改审核状态
    @Transactional
    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if(auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批未通过");
        }
//        审批之后未上架。
        product.setStatus(-1);
        this.updateById(product);
    }

    //根据id修改上架状态
    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if(status == 1) {
            product.setStatus(1);
        } else {
            product.setStatus(-1);
        }
        this.updateById(product);
    }


//    导出数据为excel
    @Override
    public void exportData(HttpServletResponse response) {
        try {

            log.info("导出数据为excel");
            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("商品数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 查询数据库中的数据
//            List<Category> categoryList = this.list();
            List<ProductVo> byPage = productMapper.findByPage(new ProductDto());

            List<ProductExcelVo> productExcelVoList = new ArrayList<>();

            // 将从数据库中查询到的Category对象转换成CategoryExcelVo对象
            for(ProductVo productVo : byPage) {
                ProductExcelVo productExcelVo = new ProductExcelVo();
                BeanUtils.copyProperties(productVo, productExcelVo, ProductExcelVo.class);
//            productExcelVo.setProductSkuList(productVo.getProductSkuList());
//            productExcelVo.setDetailsImageUrls(productVo.getDetailsImageUrls());
                productExcelVoList.add(productExcelVo);
            }
            // 写出数据到浏览器端
            EasyExcel.write(response.getOutputStream(), ProductExcelVo.class).sheet("商品数据").doWrite(productExcelVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    @Resource
    private ExcelListener<ProductExcelVo> easyExcelConfig;
    //导入数据
    @Override
    public void importData(MultipartFile file) {
        log.info("导入excel数据到数据库");
        try {
            EasyExcel.read(file.getInputStream(),ProductExcelVo.class,easyExcelConfig)
                    .sheet()  //excel中表的名称，默认为第一个sheet
                    .doRead();
            List<ProductExcelVo> productExcelVos = easyExcelConfig.getDatas();
//        将读取到的数据存入数据库中

            productExcelVos.forEach(item -> {
                ProductAddDto productDto = new ProductAddDto();
                BeanUtils.copyProperties(item,productDto);
                this.addProduct(productDto);
            });


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



}
